﻿using System;
using System.Text;
using System.Windows.Forms;

namespace MyFastDataSourceBind
{
    /// <summary>
    /// 可绑定到数据源的日期时间输入框
    /// </summary>
    public class XDBDateTimePicker : System.Windows.Forms.DateTimePicker, IXDataSourceable
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        public XDBDateTimePicker()
        {
        }


        private string strXDataFieldName = null;
        /// <summary>
        /// 绑定的数据源字段名
        /// </summary>
        [System.ComponentModel.Editor(
            typeof(XDataFieldNameEditor),
            typeof(System.Drawing.Design.UITypeEditor))]
        public string XDataFieldName
        {
            get { return strXDataFieldName; }
            set { strXDataFieldName = value; }
        }

        private string strXDataSourceName = null;
        /// <summary>
        /// 绑定的数据源名称
        /// </summary>
        [System.ComponentModel.Editor(
            typeof(XDataSourceNameEditor),
            typeof(System.Drawing.Design.UITypeEditor))]
        public string XDataSourceName
        {
            get
            {
                return strXDataSourceName;
            }
            set
            {
                strXDataSourceName = value;
                XDataSourceEventSender.Register(this, strXDataSourceName);
            }
        }

        /// <summary>
        /// 销毁对象，撤销数据源绑定
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            XDataSourceEventSender.UnRegister(this);
        }

        /// <summary>
        /// 处理数据源事件
        /// </summary>
        /// <param name="Sender">参数</param>
        /// <param name="Args">参数</param>
        public void HandleDataSourceEvent(object Sender, XDataSourceEventArgs Args)
        {
            switch (Args.Style)
            {
                case XDataSourceEventStyle.FillUI:
                    // 从数据源中获得数据并显示到用户界面上
                    this.Enabled = Args.DataSource.CanEdit(this.XDataFieldName);
                    object v = Args.DataSource.GetValue(this.XDataFieldName);
                    if (v != null && DBNull.Value.Equals(v) == false)
                    {
                        this.Value = Convert.ToDateTime(v);
                    }
                    break;
                case XDataSourceEventStyle.ReadUI:
                    // 将控件数据保存到数据源中
                    Args.DataSource.SetValue(this.XDataFieldName, this.Value);
                    break;
            }
        }
    }//public class XDBDateTimePicker
}